<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" :show-fullscreen="false" class="form-dialog" width="40%">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon icon="download" size="18" style="margin-right: 5px;"></SvgIcon>
        <span>{{ dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :model="formData"
             :rules="formRules"
             label-width="100px"
             status-icon>
      <el-form-item label="类型：" prop="type">
        <el-radio-group v-model="formData.type" @change="handleTypeChange">
          <el-radio-button :value="0">月份</el-radio-button>
          <el-radio-button :value="1">时间段</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-if="formData.type == 1" label="时间：" prop="time_range">
        <el-date-picker v-model="pickerDate"
                        :shortcuts="pickerShortcuts"
                        class="card-header-extra-action"
                        clearable
                        end-placeholder="结束日期"
                        format="YYYY-MM-DD"
                        start-placeholder="开始日期"
                        type="daterange"
                        value-format="YYYY-MM-DD"
                        @change="handleDatePickerChange"/>
      </el-form-item>
    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-permission="['shop:order:delivery']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, h, reactive, ref } from 'vue';
import { ElLoading, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { downloadFile, pickerShortcuts } from '@/utils';
import { download } from '@/utils/axios/axios-service.ts';

defineOptions({name: 'sales-download-form'})

const formRef = ref<FormInstance>();
const formLoading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

export type SalesDownload = {
  type: number;
  time_range?: string;
};
// 默认表单数据
const defaultForm: SalesDownload = <SalesDownload>{type: 0};
// 表单数据
const formData = ref({...defaultForm});
const pickerDate = ref([]);

// 表单验证规则
const formRules = reactive<FormRules>({
  type: [{required: true, message: '请选择类型', trigger: 'blur'}],
  time_range: [{required: true, message: '请选择时间范围', trigger: 'blur'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

/** 打开弹窗 */
const open = async () => {
  dialogTitle.value = '销售数据导出';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();
}
// 提供 open 方法，用于打开弹窗
defineExpose({open});

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      return
    }
    ElMessageBox.confirm(h('p', null, ['是否确认进行 ', h('span', {style: 'font-weight: bold;'}, '导出数据'), `操作吗？ `,]), '提示', {
      type: 'warning',
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }).then(() => {
      const loading = ElLoading.service({
        lock: true,
        text: '正在导出数据中...',
        background: 'rgba(0, 0, 0, 0.2)'
      })
      // 调用函数
      download('/shop/order/sales_download_excel', formData.value).then(result => {
        downloadFile(result, `销量数据`, 'xlsx')
      }).finally(() => loading.close())
    }).catch(() => {

    });

  });
};

/** 重置表单 */
const handleFormReset = () => {
  pickerDate.value = [];
  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

const handleTypeChange = () => {
  if (formData.value.type == 0) {
    pickerDate.value = [];
    formData.value.time_range = undefined;
  }
}

/** 时间范围 */
const handleDatePickerChange = (val: any) => {
  formData.value.time_range = val && val.length == 2 ? val[0] + '~' + val[1] : undefined
}

</script>

<style lang="scss" scoped>
.form-dialog {
  .el-select,
  .el-input-number {
    max-width: 13rem;
  }
}
</style>
